package com.dymedia.aibo.mvp.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Instrumentation;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.dymedia.aibo.BuildConfig;
import com.dymedia.aibo.R;
import com.dymedia.aibo.app.MainApp;
import com.dymedia.aibo.app.Product;
import com.dymedia.aibo.app.UpdateApk;
import com.dymedia.aibo.app.utils.Utils;
import com.dymedia.aibo.mvp.model.Entity.Channel;
import com.dymedia.aibo.mvp.model.Entity.Client;
import com.dymedia.aibo.mvp.model.Entity.Group;
import com.dymedia.aibo.mvp.model.Entity.Video;
import com.dymedia.aibo.mvp.presenter.ChannelPresenter;
import com.dymedia.aibo.mvp.ui.widget.MyVideoView;
import com.dymedia.aibo.mvp.ui.widget.TvMenuView;
import com.dymedia.aibo.mvp.ui.widget.VideoMenuView;
import com.dymedia.aibo.mvp.ui.widget.VideoPlayerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import me.jessyan.art.base.BaseActivity;
import me.jessyan.art.mvp.IView;
import me.jessyan.art.mvp.Message;
import me.jessyan.art.utils.ArtUtils;
import me.jessyan.art.utils.DataHelper;
import timber.log.Timber;

import static android.text.util.Linkify.WEB_URLS;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_CHANNEL;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_CLIENT;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_DATA_ERROR;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_GROUP_CHANNEL;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_GROUP_VIDEO;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_LIVE_MENU_HIDE;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_LIVE_PLAY;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_VIDEO;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_VIDEO_PLAY;
import static com.dymedia.aibo.mvp.presenter.ChannelPresenter.MSG_ACTION_VIP;
import static me.jessyan.art.utils.Preconditions.checkNotNull;


public class ChannelActivity extends BaseActivity<ChannelPresenter> implements IView {

    @BindView(R.id.videoview)
    MyVideoView videoview;
    @BindView(R.id.videoplayerView)
    VideoPlayerView videoplayerView;
    @BindView(R.id.textView_channel_num)
    TextView textView_channel_num;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.tvmenuView)
    TvMenuView tvmenuView;
    @BindView(R.id.videomenuView)
    VideoMenuView videomenuView;
    @BindView(R.id.layout_switch_mode)
    View layout_switch_mode;
    @BindView(R.id.button_live)
    View button_live;
    @BindView(R.id.button_video)
    View button_video;
    @BindView(R.id.button_more)
    View button_more;
    @BindView(R.id.logo)
    ImageView logo;
    @BindView(R.id.webview)
    WebView webview;

    Context mContext;
    Channel mCurrChannel;
    Video mCurrVideo;
    Client mClient;
    String[] mCurrChannelUrls;
    int mCurrChannelIndex=0;
    Handler mHandler = new Handler();
    private boolean isSecretMode=false;
    private boolean mIsDataReady=false;

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_channel; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mContext = this;

        //VideoAdapter.margin_top = (int)getResources().getDimension(R.dimen.videoMenu_marginTop);
        initPermission();
        videoview.setProgressBar(progressbar);
        videoview.setOnErrorListener((mp, what, extra) -> {
            videoview.hideProgressBar();
            Timber.e("MyVideoView, onErrorListener, what="+what+", extra:"+extra);
            if (mCurrChannel != null){
                if (mCurrChannelIndex < mCurrChannelUrls.length-1){
                    play(mCurrChannelUrls[++mCurrChannelIndex]);
                    showMessage(getString(R.string.switch_source)+(mCurrChannelIndex+1));
                }
            }
            return true;
        });

        tvmenuView.setCallback(Message.obtain(this));
        videomenuView.setCallback(Message.obtain(this));

        videoview.setOnPreparedListener(mp -> {
            videoview.hideProgressBar();
            mHandler.postDelayed(() -> videoview.setBackgroundColor(Color.TRANSPARENT), 200);
            mp.setOnBufferingUpdateListener((mp1, percent) -> Timber.e("dddddddd "+percent));
        });
        videoview.setOnCompletionListener(mp -> {
            Timber.d("videoView, onCompletionListener");
            videoview.hideProgressBar();
        });

        //videoview.setVideoURI(Uri.parse("http://118.89.57.38/adv/1"));
        //videoview.start();

        videoplayerView.initVideoView(videoview);
        videoplayerView.hide();

        //videoview.hideProgressBar();

        button_video.setOnClickListener(v -> {
            videoview.stop();
            switchView(VIEW_VIDEO, true, true);
        });
        button_live.setOnClickListener(v -> {
            videoview.stop();
            switchView(VIEW_LIVE, true, true);
        });
        button_more.setOnClickListener(v -> openSettingsDialog());

        //initTestData();
        mPresenter.requestSetClient(Message.obtain(this, MSG_ACTION_CLIENT, 1, 0, new Object[]{}));

        new UpdateApk(this).updateNow();

        logo.setImageResource(R.mipmap.bg);

        if (Utils.isUsaOraoUser(this) || Utils.isUsaAisaUser(this)) {
            tvmenuView.setShowGroup(false);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.removeCallbacks(this);
                    Timber.d("mPresenter = null : "+ (mPresenter == null));
                    if (mPresenter != null) {
                        mPresenter.requestChannels(Message.obtain(ChannelActivity.this, MSG_ACTION_CHANNEL, 2, 0, new Object[]{}));
                    }
                    mHandler.postDelayed(this, 9*60*1000);
                }
            }, 9*60*1000);

            mHandler.postDelayed(() -> {
                if (logo != null)
                    logo.setVisibility(View.GONE);
                if (mClient != null) {
                    int days = (int) ((mClient.vip - System.currentTimeMillis())/86400000);
                    if (mClient.vip > 0 && days >= 0 && days <= 3) {
                        showMessage(String.format("You have %d free day(s) left.\n\nVous avez %d jour(s) gratuits restant(s).", days, days));
                    }
                }
            }, 4500);
        } else {
            mHandler.postDelayed(() -> {
                if (logo != null)
                    logo.setVisibility(View.GONE);
            }, 3000);


            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHandler.removeCallbacks(this);
                    Timber.d("mPresenter = null : "+ (mPresenter == null));
                    if (mPresenter != null) {
                        mPresenter.requestSetClient(Message.obtain(ChannelActivity.this, MSG_ACTION_CLIENT, 2, 0, new Object[]{}));
                    }
                    mHandler.postDelayed(this, 9*60*1000);
                }
            }, 9*60*1000);
        }

        //        mHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                Utils.findFocusView(ChannelActivity.this);
//                mHandler.postDelayed(this, 3000);
//                //openSettingsDialog();
//            }
//        }, 6000);

//        final PackageManager packageManager = getPackageManager();
//        final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
//        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//        // get all apps
//        final List<ResolveInfo> apps = packageManager.queryIntentActivities(mainIntent, 0);
//        for (int i = 0; i <apps.size() ; i++) {
//            String name = apps.get(i).activityInfo.packageName;
//            Timber.d("name:"+name);
//        }
    }

    @Override
    public void handleMessage(@NonNull Message message) {
        checkNotNull(message);
        switch (message.what) {
            case MSG_ACTION_GROUP_VIDEO:
                mPresenter.requestVideos(Message.obtain(this, new Object[]{}));
                break;
            case MSG_ACTION_GROUP_CHANNEL:
                mPresenter.requestChannels(Message.obtain(ChannelActivity.this, MSG_ACTION_CHANNEL, 1, 0, new Object[]{}));
                break;
            case MSG_ACTION_CHANNEL:
                mIsDataReady = true;
                List<Group> data = (List<Group>) message.obj;
                if (isLiveType()) {
                    if (message.obj == null || (message.arg1 != 2)) {
                        hideLoading();
                        showView();
                    }
                    int number = DataHelper.getIntergerSF(getBaseContext(), "lastChannelNumber");
                    if (number <= 0) number = 1;
                    Object[] item = mPresenter.findChannelByNumber(number);
                    if (item != null) {
                        tvmenuView.jump((int) item[0], (int) item[1]);
                        play((Channel) item[2]);
                    }
                }
                tvmenuView.setDatas(data);
                tvmenuView.notifyDataSetChanged();
                break;
            case MSG_ACTION_VIDEO:
                mIsDataReady = true;
                hideLoading();
                showView();
                videomenuView.setDatas((List<Group>) message.obj);
                videomenuView.notifyDataSetChanged();
                break;
            case MSG_ACTION_CLIENT:
                mClient = (Client)message.obj;
                Timber.d("MSG_ACTION_CLIENT, arg1: "+message.arg1+", arg2:"+message.arg2);
                switch (message.arg1) {
                    case 1:
                        Timber.d("client, vip: "+mClient.vip);
                        refreshView();
                        break;
                    case 2:
                        if (message.arg2 == 1) { //节目有更新
                            mPresenter.requestChannels(Message.obtain(ChannelActivity.this, MSG_ACTION_CHANNEL, 2, 0, new Object[]{}));
                        }
                        break;
                }
                break;
            case MSG_ACTION_VIP:
                mClient = (Client)message.obj;
                showMessage("vip authorized, " + getString(R.string.vip_expiration_date) + new SimpleDateFormat("yyyy-MM-dd").format(new Date(mClient.vip)));
                break;
            case MSG_ACTION_LIVE_MENU_HIDE:
                hideMenuView();
                hideSwitchModeView();
                break;
            case MSG_ACTION_LIVE_PLAY:
                Channel channel = (Channel)message.obj;
                DataHelper.setIntergerSF(getBaseContext(), "lastChannelNumber", channel.number);
                play(channel);
                tvmenuView.hide();
                hideSwitchModeView();
                ((View)tvmenuView.getParent()).setVisibility(View.GONE);
                break;
            case MSG_ACTION_VIDEO_PLAY:
                Video video = (Video)message.obj;
                play(video);
                videoplayerView.initVideoView(videoview);
                switchView(VIEW_PLAYER);
                videoplayerView.setTitle(video.name);
                break;
            case MSG_ACTION_DATA_ERROR:
                if (Utils.isUsaOraoUser(this) || Utils.isUsaAisaUser(this)) {
                    openUsaOraoRegisterInfoDialog();
                }
                break;
        }
    }

    private boolean playing = false;
    @Override
    protected void onPause() {
        super.onPause();

        hideMenuView();
        hideSwitchModeView();

        playing = videoview.isPlaying();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (playing) {
            videoview.start();
            videoview.showProgressBar();
        }
    }

    @Override
    @Nullable
    public ChannelPresenter obtainPresenter() {
        return new ChannelPresenter(ArtUtils.obtainAppComponentFromContext(this));
    }

    @Override
    public void showLoading() {
        if (videoview != null)
            videoview.showProgressBar();
    }

    @Override
    public void hideLoading() {
        if (videoview != null)
            videoview.hideProgressBar();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        //ArtUtils.snackbarText(message);
        MainApp.show(24, message, true);
    }

    private void play(Channel channel) {
        mCurrChannel = channel;
        mCurrChannelIndex = 0;
        mCurrChannelUrls = channel.url.split("#");
        play(mCurrChannelUrls[0]);
    }

    private void play(Video video) {
        mCurrVideo = video;
        mCurrChannelIndex = 0;
        mCurrChannelUrls = video.url.split("#");
        play(mCurrChannelUrls[0]);
    }

    private void play(String url) {
        Timber.e("play, url: " + url);
        videoview.setVideoURI(Uri.parse(url));
        videoview.start();
        videoview.showProgressBar();
        videoview.setBackgroundColor(Color.BLACK);
        //mHandler.postDelayed(() -> videoview.hideProgressBar(), 20000);
    }

    String channelNum = "";
    long keyTimestamp = 0;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            Log.e(TAG, "dispatchKeyEvent: "+event.getKeyCode());
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_DPAD_DOWN:
                case KeyEvent.KEYCODE_DPAD_UP:
                    switch (mCurrViewMode) {
                        case VIEW_VIDEO:
                            long curr = System.currentTimeMillis();
                            if (curr - keyTimestamp < 200){
                                return true;
                            }
                            keyTimestamp = curr;
                            break;
                        case VIEW_LIVE:
                            if (!tvmenuView.isShow()) {
                                showView();
                                return true;
                            }else{
                                curr = System.currentTimeMillis();
                                if (curr - keyTimestamp < 200){
                                    return true;
                                }
                                keyTimestamp = curr;
                            }
                            break;
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    switch (mCurrViewMode) {
                        case VIEW_PLAYER:
                            videoplayerView.startPause();
                            break;
                        case VIEW_LIVE:
                            if (!tvmenuView.isShow()) {
                                new Thread(() -> new Instrumentation().sendPointerSync(MotionEvent.obtain(SystemClock.uptimeMillis(),
                                        SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 1, 1, 0))
                                ).start();
                                return true;
                            }
                            break;
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    switch (mCurrViewMode) {
                        case VIEW_PLAYER: // seek
                            mHandler.removeCallbacks(mSeekRunnable);
                            mHandler.postDelayed(mSeekRunnable, 1200);
                            videoplayerView.progress(-1);
                            break;
                        case VIEW_LIVE:
                            if (!tvmenuView.isShow() && mCurrChannel != null) {
                                if (mCurrChannelIndex > 0) {
                                    play(mCurrChannelUrls[--mCurrChannelIndex]);
                                    showMessage(getString(R.string.switch_source) + (mCurrChannelIndex + 1));
                                }
                            }
                            break;
                    }
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    switch (mCurrViewMode) {
                        case VIEW_PLAYER: // seek
                            mHandler.removeCallbacks(mSeekRunnable);
                            mHandler.postDelayed(mSeekRunnable, 1200);
                            videoplayerView.progress(1);
                            break;
                        case VIEW_LIVE:
                            if (!tvmenuView.isShow() && mCurrChannel != null) {
                                if (mCurrChannelIndex < mCurrChannelUrls.length - 1) {
                                    play(mCurrChannelUrls[++mCurrChannelIndex]);
                                    showMessage(getString(R.string.switch_source) + (mCurrChannelIndex + 1));
                                }
                            }
                            break;
                    }
                    break;
                case KeyEvent.KEYCODE_MENU:
                case KeyEvent.KEYCODE_F1:
                case KeyEvent.KEYCODE_F2:
                case KeyEvent.KEYCODE_F3:
                case KeyEvent.KEYCODE_F4:
                case KeyEvent.KEYCODE_F5:
                case KeyEvent.KEYCODE_F6:
                    openSettingsDialog();
                    break;
                case KeyEvent.KEYCODE_BACK:
                case KeyEvent.KEYCODE_DEL:
                    if (webview.getVisibility() == View.VISIBLE) {
                        webview.setVisibility(View.GONE);
                        refreshView();
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        return true;
                    }
                    if (isPlayerType()) {
                        switchView(VIEW_VIDEO);
                        return true;
                    } else if (isLiveType() && tvmenuView.isShow()) {
                        tvmenuView.hide();
                        hideMenuView();
                        hideSwitchModeView();
                    }
                    if (!exitStatus) {
                        MainApp.show(24, getString(R.string.back), false);
                        exitStatus = true;
                        mHandler.postDelayed(() -> exitStatus = false, 4000);
                        return true;
                    }
                    break;
                case KeyEvent.KEYCODE_0:
                case KeyEvent.KEYCODE_1:
                case KeyEvent.KEYCODE_2:
                case KeyEvent.KEYCODE_3:
                case KeyEvent.KEYCODE_4:
                case KeyEvent.KEYCODE_5:
                case KeyEvent.KEYCODE_6:
                case KeyEvent.KEYCODE_7:
                case KeyEvent.KEYCODE_8:
                case KeyEvent.KEYCODE_9:
                    if (isLiveType()) {
                        if (tvmenuView.isShow()) {
                            tvmenuView.hide();
                            hideMenuView();
                            hideSwitchModeView();
                        }
                        if (channelNum.length() < 4) {
                            channelNum += String.valueOf(event.getKeyCode() - KeyEvent.KEYCODE_0);
                            textView_channel_num.setVisibility(View.VISIBLE);
                            textView_channel_num.setText(channelNum);
                            mHandler.removeCallbacks(mChannelNumRunnable);
                            if (channelNum.length() == 3)
                                mHandler.postDelayed(mChannelNumRunnable, 100);
                            else
                                mHandler.postDelayed(mChannelNumRunnable, 1200);
                        }

                    }
                    break;
            }
        }

        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (isLiveType()) {
                    if (tvmenuView.isShow()) {
                        if (!Utils.isTouchPointInView(tvmenuView, (int)ev.getX(), (int)ev.getY())
                                && !Utils.isTouchPointInView(button_more, (int)ev.getX(), (int)ev.getY())
                                && !Utils.isTouchPointInView(button_live, (int)ev.getX(), (int)ev.getY())
                                && !Utils.isTouchPointInView(button_video, (int)ev.getX(), (int)ev.getY())) {
                            tvmenuView.hide();
                            hideMenuView();
                            hideSwitchModeView();
                            return true;
                        }
                    } else if (mIsDataReady){
                        tvmenuView.show();
                        showSwitchModeView();
                        return true;
                    }
                } else if (isPlayerType()) {
                    if (!videoplayerView.isShow()) {
                        videoplayerView.show();
                        return true;
                    } else if (!Utils.isTouchPointInView(videoplayerView.findViewById(R.id.layout_control), (int)ev.getX(), (int)ev.getY())) {
                        videoplayerView.hide();
                        return true;
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    Runnable mSeekRunnable = new Runnable() {
        @Override
        public void run() {
            videoplayerView.seek();
        }
    };

    boolean exitStatus = false;
    void hideChannelNum() {
        mHandler.removeCallbacks(mChannelNumRunnable);
        textView_channel_num.setVisibility(View.GONE);
    }

    Runnable mChannelNumRunnable = new Runnable() {
        @Override
        public void run() {
            hideChannelNum();
            if (!channelNum.isEmpty()) {
                Object[] item = mPresenter.findChannelByNumber(Integer.valueOf(channelNum));
                if (item != null) {
                    handleMessage(Message.obtain(ChannelActivity.this, MSG_ACTION_LIVE_PLAY, item[2]));
                }
            }
            channelNum = "";
        }
    };

    public void initPermission() {
        String[] permissions = {
                android.Manifest.permission.INTERNET,
                android.Manifest.permission.ACCESS_NETWORK_STATE,
                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
                android.Manifest.permission.WRITE_SETTINGS,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };

        ArrayList<String> toApplyList = new ArrayList<String>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, perm)) {
                toApplyList.add(perm);
                // 进入到这里代表没有权限.
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (!toApplyList.isEmpty()) {
            ActivityCompat.requestPermissions(this, toApplyList.toArray(tmpList), 123);
        }
    }

    private final int VIEW_LIVE = 0;
    private final int VIEW_VIDEO = 1;
    private final int VIEW_PLAYER = 2;
    private int mCurrViewMode = VIEW_LIVE;
    private boolean isVideoType(){return mCurrViewMode == VIEW_VIDEO;}
    private boolean isLiveType() {return mCurrViewMode == VIEW_LIVE;}
    private boolean isPlayerType() {return mCurrViewMode == VIEW_PLAYER;}

    private void showView() {
        switchView(mCurrViewMode, false, true);
    }

    private void refreshView() {
        switchView(mCurrViewMode, true, false);
    }

    private void switchView(int mode) {
        switchView(mode, false, true);
    }

    private void switchView(int mode, boolean refresh, boolean show) {
        mCurrViewMode = mode;
        Timber.d("switchView, mode: "+mode);
        switch (mode) {
            case VIEW_LIVE:
                if (show) {
                    videoview.setVisibility(View.VISIBLE);
                    tvmenuView.show();
                    videomenuView.hide();
                    hideChannelNum();
                    videoplayerView.hide();
                    //videoview.stop();
                    showSwitchModeView();
                }
                if (refresh) {
                    mPresenter.requestChannelGroups(isSecretMode, Message.obtain(ChannelActivity.this, new Object[]{}));
                    showLoading();
                }
                break;
            case VIEW_VIDEO:
                if (show) {
                    videoview.setVisibility(View.VISIBLE);
                    videomenuView.show();
                    tvmenuView.hide();
                    videoplayerView.hide();
                    videoview.stop();
                    showSwitchModeView();
                }
                if (refresh) {
                    mPresenter.requestVideoGroups(isSecretMode, Message.obtain(ChannelActivity.this, new Object[]{}));
                    showLoading();
                }
                break;
            case VIEW_PLAYER:
                if (show) {
                    tvmenuView.hide();
                    hideChannelNum();
                    videomenuView.hide();
                    hideSwitchModeView();
                }
                break;
        }
    }
    private void showSwitchModeView() {
        layout_switch_mode.setVisibility(View.VISIBLE);
        switch (mCurrViewMode) {
            case VIEW_VIDEO:
                button_live.setVisibility(View.VISIBLE);
                button_video.setVisibility(View.GONE);
                break;
            case VIEW_LIVE:
                button_live.setVisibility(View.GONE);
                button_video.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void hideSwitchModeView() {
        layout_switch_mode.setVisibility(View.GONE);
    }

    private void hideMenuView() {
        ((View)tvmenuView.getParent()).setVisibility(View.GONE);
    }
    List<Group> groups = new ArrayList<>();

    Dialog mActiveVipDialog = null;
    Dialog mSettingsDialog = null;
    Dialog mSecretDialog = null;
    Dialog mSecretChangeCodeDialog = null;

    private void openSecretChangeModeDialog(){
        View view = View.inflate(this, R.layout.dialog_input_secret, null);
        EditText editView = view.findViewById(R.id.editView_input);
        editView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setCancelable(true);
        builder.setTitle(R.string.secret_password_new);
        builder.setView(view);

        builder.setNegativeButton(R.string.cancel, (arg0, arg1) -> mSecretChangeCodeDialog.dismiss());
        builder.setPositiveButton(R.string.ok, (arg0, arg1) -> {
            String code = editView.getText().toString();
            if (code.length() < 4) {
                showMessage(getString(R.string.secret_password_4char));
                openSecretChangeModeDialog();
            } else {
                mSecretChangeCodeDialog.dismiss();
                DataHelper.setStringSF(this, "secretCode", code);
                showMessage(getString(R.string.secret_password_change_to)+code);
            }
        });

        mSecretChangeCodeDialog = builder.create();
        mSecretChangeCodeDialog.show();
    }

    private void openSecretDialog(){
        View view = View.inflate(this, R.layout.dialog_input_secret, null);
        EditText editView = view.findViewById(R.id.editView_input);
        editView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(4)});
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setCancelable(true);
        builder.setTitle(R.string.secret_mode);
        builder.setView(view);

        String secretCodeTmp = DataHelper.getStringSF(this, "secretCode");
        if (secretCodeTmp == null) secretCodeTmp = "1234";
        final String secretCode = secretCodeTmp;

        builder.setNegativeButton(R.string.cancel, (arg0, arg1) -> mSecretDialog.dismiss());
        builder.setPositiveButton(R.string.ok, (arg0, arg1) -> {
            mSecretDialog.dismiss();
            if (secretCode.equals(editView.getText().toString())){
                isSecretMode = true;
                refreshView();
                showMessage(getString(R.string.secret_switch));
            }else{
                showMessage(getString(R.string.secret_password_incorrect));
            }
        });
        builder.setNeutralButton(R.string.secret_password_change, (arg0, arg1) -> {
            mSecretDialog.dismiss();
            if (secretCode.equals(editView.getText().toString())){
                openSecretChangeModeDialog();
            }else{
                showMessage(getString(R.string.secret_password_incorrect));
            }
        });
        mSecretDialog = builder.create();
        mSecretDialog.show();
    }

    private void openActiveVipDialog(){
        View view = View.inflate(this, R.layout.dialog_input_vip, null);
        EditText editView = view.findViewById(R.id.editView_input);
        editView.setFilters(new InputFilter[]{new InputFilter.LengthFilter(8)});
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setCancelable(true);
        builder.setTitle(R.string.vip_active);
        builder.setView(view);

        builder.setNegativeButton(R.string.cancel, (arg0, arg1) -> mActiveVipDialog.dismiss());
        builder.setPositiveButton(R.string.ok, (arg0, arg1) -> {
            mActiveVipDialog.dismiss();
            mPresenter.requestActiveVip(Message.obtain(this, editView.getText().toString()));
        });
        mActiveVipDialog = builder.create();
        mActiveVipDialog.show();
    }

    private void openSettingsDialog(){
        View view = View.inflate(this, R.layout.dialog_menu, null);
        TextView textView_uid = view.findViewById(R.id.textView_uid);
        textView_uid.setText(mClient == null ? "" : mClient.uid + "/"+Utils.getCode(this)+"/"+BuildConfig.VERSION_NAME);
        TextView textView_vip = view.findViewById(R.id.textView_vip);
        String vip = getString(R.string.vip_expiration_date)+getString(R.string.vip_expired);
        if (mClient != null && mClient.vip > 0){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            vip = getString(R.string.vip_expiration_date)+formatter.format(new Date(mClient.vip));
        }
        textView_vip.setText(vip);

        view.findViewById(R.id.button_vip).setOnClickListener(v -> {
            mSettingsDialog.dismiss();
            openActiveVipDialog();
        });
        view.findViewById(R.id.button_secret).setOnClickListener(v -> {
            mSettingsDialog.dismiss();
            openSecretDialog();
        });

        RadioGroup vvv = view.findViewById(R.id.radiogroup_type);
        vvv.check(isVideoType() ? R.id.radiobutton_video : R.id.radiobutton_channel);
        RadioButton checkedView = view.findViewById(vvv.getCheckedRadioButtonId());
        //checkedView.setText(checkedView.getText()+"√");
        checkedView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG );
        checkedView.requestFocus();
        vvv.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId){
                case R.id.radiobutton_channel:
                    if (!isLiveType())
                        switchView(VIEW_LIVE);
                    mSettingsDialog.dismiss();
                    break;
                case R.id.radiobutton_video:
                    if (!isVideoType())
                        switchView(VIEW_VIDEO);
                    mSettingsDialog.dismiss();
                    break;
            }
        });
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        builder.setCancelable(true);
        //builder.setTitle("Vip authorization code");
        builder.setView(view);
        mSettingsDialog = builder.create();
        mSettingsDialog.show();

        Window dialogWindow = mSettingsDialog.getWindow();
        dialogWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = MATCH_PARENT;
        lp.height = MATCH_PARENT;
        dialogWindow.setAttributes(lp);

    }

//    private void openUsaOraoRegisterInfoDialog(){
//        TextView view = new TextView(this);
//        view.setTextColor(Color.RED);
//        view.setTextSize(24);
//        view.setPadding(60, 40, 20, 40);
//        view.setAutoLinkMask(WEB_URLS);
//
//        final SpannableStringBuilder style = new SpannableStringBuilder();
//        String text = String.format(getString(mClient.registerTime > 0 ? R.string.pay_url : R.string.reg_url), Utils.getUid());
//        style.append(text);
//
//        int index1 = text.indexOf("CLICK HERE");
//        int index3 = text.indexOf("CLIQUEZ ICI");
//        int index5 = text.indexOf("3 days FREE", index3+11);
//
//        String regUrl = "TPLDHEZP".equals(Utils.getCode(this)) ? "https://www.oraoplay.com/myaccount/register.php?mac=" : "https://www.hub-telecoms.com/myaccount/register.php?mac=";
//        String payUrl = "TPLDHEZP".equals(Utils.getCode(this)) ? "https://www.oraoplay.com/myaccount/pay.php?pmac=" : "https://www.hub-telecoms.com/myaccount/pay.php?pmac=";
//
//        //设置部分文字点击事件
//        ClickableSpan clickableSpan = new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//                Intent intent = new Intent();
//                intent.setData(Uri.parse(regUrl+Utils.getUid()));
//                intent.setAction(Intent.ACTION_VIEW);
//                startActivity(intent);
//                finish();
//            }
//        };
//        style.setSpan(clickableSpan, index1, index1+11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        ClickableSpan clickableSpan3 = new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//                Intent intent = new Intent();
//                intent.setData(Uri.parse(payUrl+Utils.getUid()));
//                intent.setAction(Intent.ACTION_VIEW);
//                startActivity(intent);
//            }
//        };
//        style.setSpan(clickableSpan3, index3, index3+11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//        view.setText(style);
//        //设置部分文字颜色
//        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.WHITE);
//        style.setSpan(foregroundColorSpan, index1, index1+11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        ForegroundColorSpan foregroundColorSpan3 = new ForegroundColorSpan(Color.WHITE);
//        style.setSpan(foregroundColorSpan3, index3, index3+11, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        ForegroundColorSpan foregroundColorSpan5 = new ForegroundColorSpan(Color.YELLOW);
//        if (index5 > 0)
//            style.setSpan(foregroundColorSpan5, index5, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        //配置给TextView
//        view.setMovementMethod(LinkMovementMethod.getInstance());
//        view.setText(style);
//
////        view.setText(String.format("CLICK HERE and CLIQUEZ ICI will jump to %s%s\n\nHERE TO MAKE A PAYMENT and ICI POUR FAIRE UN PAIEMENT will jump to %s%s",
////                getString(R.string.reg_url),
////                getString(R.string.pay_url),
////                Utils.getUid(),
////                Utils.getUid()));
//
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
//        builder.setCancelable(true);
//        //builder.setTitle(R.string.app_name);
//        builder.setView(view);
//        mSettingsDialog = builder.create();
//        mSettingsDialog.show();
//
//        Window dialogWindow = mSettingsDialog.getWindow();
//        dialogWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        lp.width = MATCH_PARENT;
//        lp.height = MATCH_PARENT;
//        dialogWindow.setAttributes(lp);
//    }

//    private void openUsaOraoRegisterInfoDialog() {
//        Timber.d("openUsaOraoRegisterInfoDialog");
//        View view = LayoutInflater.from(this).inflate(R.layout.dialog_orao,null);
//        String regUrl = "TPLDHEZP".equals(Utils.getCode(this)) ? "https://www.oraoplay.com/myaccount/register.php?mac=" : "https://www.hub-telecoms.com/myaccount/register.php?mac=";
//        String payUrl = "TPLDHEZP".equals(Utils.getCode(this)) ? "https://www.oraoplay.com/myaccount/pay.php?pmac=" : "https://www.hub-telecoms.com/myaccount/pay.php?pmac=";
//        String url = mClient.registerTime > 0 ? payUrl : regUrl;
//        WebView webview = view.findViewById(R.id.webview);
//        webview.setWebViewClient(new WebViewClient());
//        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//        webview.getSettings().setUseWideViewPort(true);
//        //webview.loadUrl(url+Utils.getUid());
//        webview.loadUrl("http://www.baidu.com");
//
//        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
//        builder.setCancelable(true);
//        //builder.setTitle(R.string.app_name);
//        builder.setView(view);
//        Dialog dialog = builder.create();
//        dialog.setOnCancelListener(dialog1 -> refreshView());
//        dialog.show();
//        Window dialogWindow = dialog.getWindow();
//        dialogWindow.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//        lp.width = MATCH_PARENT;
//        lp.height = MATCH_PARENT;
//        dialogWindow.setAttributes(lp);
//        mHandler.post(() -> {
//            webview.setVisibility(View.VISIBLE);
//            webview.requestFocus(View.FOCUS_DOWN);
//            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//        });
//    }
    private void openUsaOraoRegisterInfoDialog() {
        Timber.d("openUsaOraoRegisterInfoDialog");
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        mHandler.postDelayed(() -> {
            if (logo != null)logo.setVisibility(View.GONE);
            if (webview != null) {
                String regUrl = Product.getProduct(this).regUrl();
                String payUrl = Product.getProduct(this).payUrl();
                String url = mClient.registerTime > 0 ? payUrl : regUrl;
                webview.setVisibility(View.VISIBLE);
                webview.loadUrl(url+Utils.getUid());
                //webview.loadUrl("http://www.jd.com");
                webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
                webview.getSettings().setUseWideViewPort(true);
                webview.setVerticalScrollBarEnabled(true);
                webview.setWebViewClient(new WebViewClient(){
                    @Override
                    public void onPageFinished(WebView view, String url){
                        super.onPageFinished(view, url);
                        hideLoading();
                    }
                });
            }
        }, 100);
    }
}
